<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="部门ID" prop="deptId">
            <el-input
              v-model="baTable.form.items!.deptId"
              placeholder="请输入部门ID"
              disabled
            />
          </el-form-item>
          <el-form-item label="车间名称" prop="name">
            <el-input
              v-model="baTable.form.items!.name"
              placeholder="请输入车间名称"
              disabled
            />
            <div class="block-help">工作中心描述</div>
          </el-form-item>
          <el-form-item label="设备型号" prop="equipmentName">
            <el-input
              class="filterInput"
              v-model="filterText"
              placeholder="关键词过滤"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRef"
                class="filter-tree"
                :data="state.modelOptions"
                :props="{ label: 'modelCode', value: 'id' }"
                node-key="modelCode"
                show-checkbox
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.equipmentType]
                    : []
                "
                :filter-node-method="filterNode"
                @check="rightClick"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="设备编码" prop="equipmentCode">
            <el-input
              v-model="baTable.form.items!.equipmentCode"
              placeholder="请输入唯一设备编码"
            />
          </el-form-item>
          <el-form-item prop="equipmentName" label="设备名称">
            <el-input
              v-model="baTable.form.items!.equipmentName"
              placeholder="请选择设备型号"
              disabled
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="额定运行时间/小时" prop="runTime">
            <el-input
              v-model="baTable.form.items!.runTime"
              type="number"
              placeholder="请输入设备额定运行时间"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="工序列表" prop="processIds">
            <el-select
              v-model="baTable.form.items!.processIds"
              multiple
              placeholder="可自定义设备工序"
              @change="modelChange"
            >
              <el-option
                v-for="item in state.processOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单人/班组" prop="classType">
            <el-select
              v-model="baTable.form.items!.classType"
              placeholder="请选择单人/班组"
              @change="classTypeChange"
            >
              <el-option
                v-for="item in state.scheduleTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="equipmentType" label="设备型号">
            <el-input
              v-model="baTable.form.items!.equipmentType"
              type="string"
              placeholder="请输入设备型号"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="网关绑定" prop="gatewaycode">
            {{ baTable.form.items!.gatewaycode }}
            <el-button
              v-if="baTable.form.operate === 'edit' && !state.bank"
              type="primary"
              style="margin-left: 10px"
              @click="unbind"
              >解绑</el-button
            >
            <el-input
              v-else
              v-model="filterTextIOT"
              placeholder="输入网关编号进行过滤"
              style="background: whitesmoke"
            />
            <el-scrollbar
              v-else
              ref="verticalMenusIOTRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRefIot"
                class="filter-tree"
                :data="state.iotList"
                :props="{ label: 'code', value: 'code', disabled: 'bank' }"
                node-key="code"
                show-checkbox
                default-expand-all
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.gatewaycode]
                    : []
                "
                :filter-node-method="filterNodeIOT"
                @check="iotClick"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span style="margin-left: 18px; color: yellowgreen">{{
                      !data.bank ? "未绑定" : "已绑定"
                    }}</span>
                  </span>
                </template>
              </el-tree>
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="额定功率(kw)" prop="power">
            <el-input
              v-model="baTable.form.items!.power"
              placeholder="请输入额定功率"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="user">
            <el-input
              v-model="baTable.form.items!.user"
              placeholder="维护人员信息"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="userPhone">
            <el-input
              v-model="baTable.form.items!.userPhone"
              placeholder="维护人员联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="心跳时长(ms)" prop="hearttime">
            <el-input
              v-model="baTable.form.items!.hearttime"
              placeholder="请输入心跳时长"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  inject,
  onMounted,
  watch,
  computed,
  nextTick,
} from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import { ElButton } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { changeBankToNumber } from "@/utils/common";
import { ElNotification } from "element-plus";

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const station = inject("station") as any;
const equipUnit = inject("equipUnit") as any;
const bomP = inject("bomP") as any;
const bomR = inject("bomR") as any;
const config = useConfig();
const model = inject("model") as any;
const accessPoint = inject("accessPoint") as any;
const treeRefIot = ref<InstanceType<typeof ElTree>>();
const filterTextIOT = ref(""); //网关

const state: {
  modelOptions: anyObj[];
  iotList: anyObj[];
  processOptions: anyObj[];
  bank: boolean;
  scheduleTypeOptions: anyObj[];
} = reactive({
  modelOptions: [], //设备类型列表
  processOptions: [], //工序列表
  iotList: [], //网关列表
  bank: false,
  scheduleTypeOptions: [
    {
      value: "单人",
      label: "单人",
    },
    {
      value: "班组",
      label: "班组",
    },
  ], //排班方式列表
});
const treeRef = ref<InstanceType<typeof ElTree>>();

const filterText = ref(""); //设备型号关键词过滤
const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.modelCode.includes(value);
};

// 选择设备型号
const rightClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  console.log("型号选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    baTable.form.items!.equipmentName = MouseEvent.modelName;
    baTable.form.items!.equipmentType = MouseEvent.modelCode;
  } else {
    baTable.form.items!.equipmentName = "";
    baTable.form.items!.equipmentType = "";
  }
};

const rules = reactive<FormRules>({
  deptId: [{ required: true, message: "部门ID不能为空", trigger: "blur" }],
  name: [{ required: true, message: "车间名称不能为空", trigger: "blur" }],
  processIds: [
    { required: true, message: "工序列表不能为空", trigger: "blur" },
  ],
  classType: [
    { required: true, message: "单人/班组不能为空", trigger: "blur" },
  ],
  // processCodes: [
  //   { required: true, message: "工序列表不能为空", trigger: "blur" },
  // ],
  // runTime: [
  //   { required: true, message: "额定运行时间不能为空", trigger: "blur" },
  // ],
  equipmentCode: [
    { required: true, message: "设备编码不能为空", trigger: "blur" },
  ],
  equipmentName: [
    { required: true, message: "设备名称不能为空", trigger: "blur" },
  ],
  equipmentType: [
    { required: true, message: "设备型号不能为空", trigger: "blur" },
  ],
});

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

//排班方式
const classTypeChange = (val: any) => {
  baTable.form.items!.classType = val;
  console.log("排班方式", val);
};

//解绑
const unbind = () => {
  accessPoint.unbind(baTable.form.items.gatewaycode).then((res: any) => {
    state.bank = true;
    nextTick(() => {
      accessPoint.getIOTList({}).then((res: any) => {
        console.log("网关列表篇", res);
        state.iotList = changeBankToNumber(res.rows);
      });
    });
  });
};
//网关
const filterNodeIOT = (value: string, data: any) => {
  console.log("网关", value, data);
  if (!value) return true;
  return data.code.includes(value);
};
const iotClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  console.log("网关选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    if (object.checkedKeys.length > 1) {
      ElNotification({
        type: "warning",
        message: "只能选择一个网关进行绑定",
      });
      return;
    }
    baTable.form.items!.gatewaycode = MouseEvent.code; //网关编号
    baTable.form.items!.cardnumber = MouseEvent.cardNumber; //流量卡号
  } else {
    console.log("取消绑定网关", baTable.form.items);
    baTable.form.items!.gatewaycode = ""; //网关编号为空
    baTable.form.items!.cardnumber = ""; //流量卡号为空
  }
};

//工序选择
const modelChange = (val: any) => {
  baTable.form.items!.processIds = val;
  console.log("类型", val);
};

onMounted(() => {
  //获取设备类型列表
  model.getList({ pageSize: 1000 }).then((res: any) => {
    state.modelOptions = res.rows;
    console.log("获取设备类型列表", res);
  });
  //获取工序列表
  bomP
    .getRouteList({ pageSize: 10000 })
    .then((res: any) => {
      console.log("获取工序列表", res);
      state.processOptions = res.rows;
    })
    .catch((err: any) => {});
  setTimeout(() => {
    baTable.form.items!.deptId = equipUnit.stationInfo.id;
    baTable.form.items!.name = equipUnit.stationInfo.label;
    console.log("设备单元", equipUnit.stationInfo);
  });
});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
watch(filterTextIOT, (val) => {
  treeRefIot.value!.filter(val);
});
</script>
<style lang="scss" scoped>
.filter-tree {
  height: 200px;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
